package com.easymin.weixin.controller.v5;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easymin.weixin.common.WxUtils;
import com.easymin.weixin.common.api.DaijiaApi;
import com.easymin.weixin.common.api.FreightApi;
import com.easymin.weixin.controller.v5.utils.ErrorMapV5;
import com.easymin.weixin.controller.v5.utils.ResultV5;
import com.easymin.weixin.entity.WxAccount;
import com.easymin.weixin.entity.WxApplication;
import com.easymin.weixin.manager.WxAccountManager;
import com.easymin.weixin.manager.WxApplicationManager;
import com.google.common.base.Preconditions;

/**
 * 货运请求控制器
 * @author zane
 *
 */
@Controller
@RequestMapping("v5/huoyun/")
public class HuoYunController {
	
	private static final String WX_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";

	private static final String WX_JSAPI_TICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={access_token}&type=jsapi";
	
	@Autowired
	private WxApplicationManager wxApplicationManager;
	
	@Autowired
	private WxAccountManager wxAccountManager;
	
	@Autowired
	private FreightApi freightApi;
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
	private DaijiaApi daijiaApi;


	/**
	 * 获取货运优惠券
	 * @param appKey 系统key
	 * @param passengerId 用户ID
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="getCoupons", method={RequestMethod.GET})
	public ResultV5 getCoupons (
			@RequestParam(required = true, value = "appKey") String appKey,
			@RequestParam(required = true, value = "passengerId") Long passengerId) {
		
		try {
			WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
			String server = wxApplication.getAddress();
			
			JSONObject json = freightApi.getCoupons(server, passengerId);
			if (null == json) {
				return ErrorMapV5.ERR_GET_FREIGHT_COUPONS;
			}
			
			JSONArray data = json.getJSONArray("data");
			ResultV5 result = ErrorMapV5.ERR_SUCCESS.clone();
			result.setData(data);
			return result;

		} catch (Exception e) {
			e.printStackTrace();
			return ErrorMapV5.ERR_SYSTEM;
		}
	}
	
	/**
	 * 获取订单评价
	 * @param appKey 系统Key
	 * @param orderId 订单号
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="getReview", method={RequestMethod.GET})
	public ResultV5 getReview (
			@RequestParam(required = true, value = "appKey") String appKey,
			@RequestParam(required = true, value = "orderId") Long orderId) {
		
		try {
			JSONObject json = freightApi.getFreightReview(appKey, orderId);
			if (null == json) {
				return ErrorMapV5.ERR_GET_FREIGHT_REVIEW;
			}
			JSONObject data = json.getJSONObject("data");
			ResultV5 result = ErrorMapV5.ERR_SUCCESS.clone();
			result.setData(data);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return ErrorMapV5.ERR_SYSTEM;
		}
	}
	
	/**
	 * 获取用户未完成订单
	 * @param passengerId 用户ID
	 * @param appKey 系统Key
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="getNotSuccessOrders", method={RequestMethod.GET})
	public ResultV5 getNotSuccessOrders (
			@RequestParam(required=true, value="passengerId") Long passengerId,
			@RequestParam(required=true, value="appKey")String appKey) {
		
		try {
			
			JSONObject json = freightApi.getNotSuccessOrders(passengerId, appKey);
			if (null == json) {
				return ErrorMapV5.ERR_GET_FREIGHT_NOT_SUCCESS_ORDERS;
			}
			
			ResultV5 result = ErrorMapV5.ERR_SUCCESS.clone();
			result.setData(json.getJSONArray("data"));
			return result;
			
		} catch (Exception e) {
			e.printStackTrace();
			return ErrorMapV5.ERR_SYSTEM;
		}
	}
	
	/**
	 * 微信支付
	 * @param appKey 系统Key
	 * @param orderId 订单ID
	 * @param openId openid
	 * @param appId 微信appId
	 * @param request 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="doPayForWx", method={RequestMethod.POST})
	public ResultV5 wxPay (
			@RequestParam(required = true, value = "appKey") String appKey,
			@RequestParam(required = true, value = "orderId") Long orderId,
			@RequestParam(required = true, value = "openId") String openId,
			@RequestParam(required = true, value = "appId") String appId, 
			HttpServletRequest request) {
		
		ResultV5 result = null;
		try {
			WxApplication wxApplication = wxApplicationManager.findByAppKey(appKey);
			Preconditions.checkArgument(null != wxApplication, "appKey错误");

			WxAccount wxAccount = wxAccountManager.findBy(appId, wxApplication.getId());
			Preconditions.checkArgument(null != wxAccount, "appid错误");

			// 判断是否来自微信
			StringBuilder sb = new StringBuilder();
			sb.append(request.getScheme());
			sb.append("://");
			sb.append(request.getServerName());
			int port = request.getServerPort();
			if (port != 80) {
				sb.append(":").append(port);
			}
			sb.append(request.getRequestURI());
			String queryString = request.getQueryString();
			if (StringUtils.isNotBlank(queryString)) {
				sb.append("?");
				sb.append(queryString);
			}

			JSONObject jsonObject = new JSONObject();
			JSONObject jo = freightApi.getFreightWxPrepayId(wxApplication.getAddress(), orderId, openId);
			jsonObject.put("package", jo.getString("package"));
			jsonObject.put("timestamp", jo.getString("timeStamp"));
			jsonObject.put("url", sb.toString());
			jsonObject.put("nonceStr", jo.getString("nonceStr"));
			jsonObject.put("paySign", jo.getString("paySign"));

			// 获取微信AccessToken
			String response = restTemplate.getForObject(WX_ACCESS_TOKEN, String.class, wxAccount.getWxappId(),
					wxAccount.getAppsecret());
			JSONObject ac = JSON.parseObject(response);

			if (ac.containsKey("access_token")) {
				String accessToken = ac.getString("access_token"); // 获取微信access_token
				// 获取jsapi_ticket
				String resp = restTemplate.getForObject(WX_JSAPI_TICKET, String.class, accessToken);
				JSONObject ticketJson = JSON.parseObject(resp);
				if (ticketJson.containsKey("ticket")) {
					String ticket = ticketJson.getString("ticket");
					jsonObject.put("jsapi_ticket", ticket);
					Map<String, Object> signParams = new HashMap<>();
					signParams.put("jsapi_ticket", ticket);
					signParams.put("timestamp", jo.getString("timestamp"));
					signParams.put("url", sb.toString());
					signParams.put("noncestr", jo.getString("noncestr"));
					jsonObject.put("signature", WxUtils.buildSha1Sign(signParams));

					result = ErrorMapV5.ERR_SUCCESS.clone();
					result.setData(jsonObject);
					return result;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ErrorMapV5.ERR_SYSTEM;
		}
		
		return null;
	}
}
